package com.exam.tencent;

import java.util.ArrayList;
import java.util.Arrays;



/**
 * date:
 * description:
 */
public class Solution2 {
    /**
     * 代码中的类名、方法名、参数名已经指定，请勿修改，直接返回方法规定的值即可
     *
     * @param a int整型一维数组
     * @return int整型
     */
    public int getNumber (int[] a) {
        int n = a.length;
        boolean[] primeIndex = findPrimeIndex(n);
        int len = n;
        ArrayList<Integer> list = new ArrayList<>();
        for (int i = 0; i < n; i++) {
            list.add(a[i]);
        }
        //ArrayList<Integer> res = new ArrayList<>();
        while(len > 1){
            ArrayList<Integer> res = new ArrayList<>();
            for (int i = 0; i < len; i++) {
                if(primeIndex[i + 1]){
                    res.add(list.get(i));
                }
            }
            len = res.size();
            list = new ArrayList<>(res);
        }
        // write code here
        return list.get(0);
    }

    private boolean[] findPrimeIndex(int n) {
        boolean[] isPrime = new boolean[n + 1];
        Arrays.fill(isPrime, true);
        isPrime[0] = false;
        isPrime[1] = false;
        for (int i = 2; i <= n; i++) {
            if(!isPrime[i]){
                continue;
            }
            for (int j = 2; i * j <= n; j++) {
                isPrime[i * j] = false;
            }
        }
        return isPrime;
    }

    public static void main(String[] args) {
        Solution2 instance = new Solution2();
        //int res = instance.getNumber(new int[]{1, 2, 3, 4});
        int res = instance.getNumber(new int[]{3,1,1,4,5,6});
        System.out.println(res);
    }
}
